package mylab.starters.mybatis.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import mylab.base.constants.DbConst;
import mylab.base.model.entity.Entity;
import mylab.common.context.UserContext;
import mylab.usm.api.model.account.User;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

/**
 * 自动填充字段
 */
@Slf4j
@Component
public class AutoMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        if (isEntity(metaObject) || !openInsertFill()) {
            return;
        }

        log.debug("插入时，自动填充...");
        this.strictInsertFill(metaObject, DbConst.PROPERTY_OWNER, String.class, getOwner());
        this.strictInsertFill(metaObject, DbConst.PROPERTY_CREATER, String.class, getCreater());
        this.strictInsertFill(metaObject, DbConst.PROPERTY_UPDATER, String.class, getUpdater());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (isEntity(metaObject) || !openUpdateFill()) {
            return;
        }

        log.debug("更新时，自动填充...");
        this.strictUpdateFill(metaObject, DbConst.PROPERTY_UPDATER, String.class, getUpdater());
    }

    private String getOwner() {
        return String.valueOf(getUser().getId());
    }

    private String getCreater() {
        return String.valueOf(getUser().getId());
    }

    private String getUpdater() {
        return String.valueOf(getUser().getId());
    }

    private User getUser() {
        return UserContext.getUser();
    }

    private static boolean isEntity(MetaObject metaObject) {
        return !(metaObject.getOriginalObject() instanceof Entity);
    }

}
